package com.hj.tools;

import org.springframework.stereotype.Component;

/**
 * @author < a href="huajian2018@aliyun.com">hj</ a>
 * @Description 雪花算法生成主键ID
 */
@Component
public class SnowFlakeUtil {


//下面两个每个5位，加起来就是10位的工作机器id
    /**
     * 工作id
     */
    private long workerId = 3L;
    /**
     * 数据id
     */
    private long dataCenterId = 3L;
    /**
     * 12位的序列号
     */
    private long sequence = 3L;

    /**
     * 长度为5位
     */
    private final long workerIdBits = 5L;
    private final long dataCenterIdBits = 5L;

    /**
     * 上次时间戳，初始值为负数
     */
    private long lastTimestamp = -1L;

    /**
     * 初始时间戳
     */
    long initialTimestamp = 738266400000L;

    public SnowFlakeUtil() {
    }

    public SnowFlakeUtil(long workerId, long dataCenterId, long sequence) {
        // 检验工作id
        // 最大值
        long maxWorkerId = ~(-1L << workerIdBits);
        long maxDataCenterId = ~(-1L << dataCenterIdBits);
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
        }
        if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("dataCenterId can't be greater than %d or less than 0", maxDataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        this.sequence = sequence;
    }

    public long getTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 下一个ID生成算法
     *
     * @return ID
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        //获取当前时间戳如果小于上次时间戳，则表示时间戳获取出现异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - timestamp));
        }
        //获取当前时间戳如果等于上次时间戳（同一毫秒内），则在序列号加一；否则序列号赋值为0，从0开始。
        long sequenceBits = 12L;
        if (lastTimestamp == timestamp) {
            long sequenceMask = ~(-1L << sequenceBits);
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        //将上次时间戳值刷新
        lastTimestamp = timestamp;


        /*
         * 返回结果：
         * (timestamp - initialTimestamp) << timestampLeftShift) 表示将时间戳减去初始时间戳，再左移相应位数
         * (dataCenterId << dataCenterIdShift) 表示将数据id左移相应位数
         * (workerId << workerIdShift) 表示将工作id左移相应位数
         * | 是按位或运算符，例如：x | y，只有当x，y都为0的时候结果才为0，其它情况结果都为1。
         * 因为个部分只有相应位上的值有意义，其它位上都是0，所以将各部分的值进行 | 运算就能得到最终拼接好的id
         */
        long dataCenterIdShift = sequenceBits + workerIdBits;
        long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
        return ((timestamp - initialTimestamp) << timestampLeftShift) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << sequenceBits) |
                sequence;
    }

    /**
     * 获取时间戳，并与上次时间戳比较
     *
     * @param lastTimestamp 上次时间戳
     * @return 时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 获取系统时间戳
     *
     * @return 时间戳
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }


}
